package com.zy.www.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.extension.uploader.ClientUploader;
import com.aliyuncs.green.model.v20180509.DetectFaceRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.zy.www.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zy
 * 人脸属性检测：本地图片文件检测样例
 */
@Slf4j
@Service
public class DetectFaceFileService {

    public List<User> checkImg(String imgPath) throws Exception {
        //请替换成你自己的accessKeyId、accessKeySecret
        IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", "LTAI4FrWLNukX3mkEwBaKS42", "9MdjoBfnUcf58DL2iGFdUvLwZBKMPw");
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        DetectFaceRequest detectFaceRequest = new DetectFaceRequest();
        detectFaceRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        detectFaceRequest.setMethod(MethodType.POST); // 指定请求方法
        detectFaceRequest.setEncoding("utf-8");
        detectFaceRequest.setHttpContentType(FormatType.JSON);

        ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);

        String url1 = null;
        try {
            //上传待检测人脸图片
            url1 = clientUploader.uploadFile(imgPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject data = new JSONObject();
        // 设置待检测的人脸图片
        data.put("url", url1);
        detectFaceRequest.setHttpContent(data.toJSONString().getBytes(StandardCharsets.UTF_8), "UTF-8", FormatType.JSON);

        /**
         * 请设置超时时间, 服务端全链路处理超时时间为10秒，请做相应设置
         * 如果您设置的ReadTimeout小于服务端处理的时间，程序中会获得一个read timeout异常
         */
        detectFaceRequest.setConnectTimeout(3000);
        detectFaceRequest.setReadTimeout(10000);

        HttpResponse httpResponse;
        try {
            httpResponse = client.doAction(detectFaceRequest);
        } catch (Exception e) {
            log.error("处理异常", e);
            return Collections.emptyList();
        }

        // 判断HTTP请求是否成功
        if (httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), StandardCharsets.UTF_8));
            if (200 == scrResponse.getInteger("code")) {
                JSONObject result = scrResponse.getJSONObject("data");
                if (200 == result.getInteger("code")) {
                    /**
                     *   结果数据
                     */
                    JSONArray faces = result.getJSONArray("faces");
                    // 检测到的人脸个数
                    System.out.println("faceCount:" + faces.size());
                    // 每个人脸的结果详情
                    List<User> users = new ArrayList<>();
                    for (int i = 0; i < faces.size(); i++) {
                        User user = JSON.parseObject(faces.getJSONObject(i).toJSONString(), User.class);
                        users.add(user);
                        System.out.println("face" + i + ": " + faces.getJSONObject(i).toJSONString());
                    }
                    return users;
                } else {
                    System.out.println("result fail: " + result.toJSONString());
                }
            } else {
                /**
                 * 请求整体处理失败，原因视具体的情况详细分析
                 */
                System.out.println("request fail:" + scrResponse.toJSONString());
            }
        } else {
            /**
             * HTTP 请求失败，错误详情
             */
            System.out.println("response fail!" +
                    "\ncode:" + httpResponse.getStatus() +
                    "\nmsg:" + new String(httpResponse.getHttpContent(), StandardCharsets.UTF_8));
        }
        log.error("出错了......");
        return Collections.emptyList();
    }
}